<?

class Auth extends Core {

	protected $model = 'usuarios';
	protected $user_field = 'user';
	protected $pass_field = 'pass';
	protected $encription = 'md5';
	protected $prefix = '';
	public $redirect_ok = '/admin/dta/browse';
	public $redirect_error = '/admin';

	function __construct () {
		parent::__construct();

		if ($this->load->prefix()) {
			$router = Router::getInstance();
			$this->prefix = $router->prefixName($this->load->prefix()).'_';
		}
	}

	function login ($user, $pass) {
		// Si hay definida una funcion de encriptacion, la ejecuto
		if ($this->encription)
			$pass = call_user_func($this->encription, $pass);

		// Obtengo el modelo 
		$model = $this->load->model($this->model);
		// Agrego los filtros
		$model->addFilter($this->user_field." : '$user'");
		$model->addFilter($this->pass_field." : '$pass'");
		// Limit 1
		$model->limit(1,1);

		// Obtengo los datos del usuario
		if (!$data = $model->browse()) {
			if ($this->redirect_error) {
				$router = Router::getInstance();
				$router->redirect($this->redirect_error);
			}
			return false;
		}
			
		// Si tiene datos, los almaceno en sesion
		$this->Session->set($this->prefix.'usuario', current($data));

		// Si tiene datos, los almaceno en sesion
		$this->Session->set($this->prefix.'logged', true);

		if ($this->redirect_ok) {
			$router = Router::getInstance();
			$router->redirect($this->redirect_ok);
		}
	}
	
	function logout () {
		$this->Session->del($this->prefix.'usuario');
		$this->Session->del($this->prefix.'logged');
	}
	
	function is_logged () {
		return $this->Session->get($this->prefix.'logged');
	}

	function whoami () {
		return $this->Session->get($this->prefix.'usuario');
	}

}

?>
